import type { RouteRecordRaw } from 'vue-router'

import { calcFirstValidPath } from '@/store/modules/helper'
import { usePermissionStoreWithOut } from '@/store/modules/permission'
import { useNProgress } from '@fl/hooks/web/useNProgress'
import { usePageLoading } from '@fl/hooks/web/usePageLoading'
import { useTitle } from '@fl/hooks/web/useTitle'
import { useAppStoreWithOut } from '@fl/store/modules/app'
import { useUserStoreWithOut } from '@fl/store/modules/user'

import router from './router'

const { done, start } = useNProgress()

const { loadDone, loadStart } = usePageLoading()

router.beforeEach(async (to, from, next) => {
    start()
    loadStart()
    const permissionStore = usePermissionStoreWithOut()
    const _appStore = useAppStoreWithOut()
    const userStore = useUserStoreWithOut()
    if (userStore.getUserInfo) {
        if (to.path === '/login') {
            next({ path: '/' })
        }
        else {
            if (permissionStore.getIsAddRouters) {
                next()
                return
            }

            // 动态生成头部导航
            permissionStore.generateHeaderMenu()

            // 企业端生成静态路由
            await permissionStore.generateRoutes('static')

            permissionStore.getAddRouters.forEach((route) => {
                router.addRoute(route as unknown as RouteRecordRaw) // 动态添加可访问路由表
            })
            let redirectPath = from.query.redirect || to.path
            // 根路由重定向到第一个可访问路由
            if (redirectPath === '/')
                redirectPath = calcFirstValidPath()

            const redirect = decodeURIComponent(redirectPath as string)
            const nextData = to.path === redirect ? { ...to, replace: true } : { path: redirect }
            permissionStore.setIsAddRouters(true)
            next(nextData)
        }
    }
    else {
        if (['/login'].includes(to.path))
            next()
        else
            next(`/login?redirect=${to.path}`) // 否则全部重定向到登录页
    }
})

router.afterEach((to) => {
    useTitle(to?.meta?.title as string)
    done() // 结束Progress
    loadDone()
})
